package com.gulimall.cart.controller;

import com.common.to.OrderItemTo;
import com.gulimall.cart.Interceptor.CartInterceptor;
import com.gulimall.cart.service.imp.CartServiceImpl;
import com.gulimall.cart.to.UserInfoTo;
import com.gulimall.cart.vo.CartItemVo;
import com.gulimall.cart.vo.CartVo;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author Rookie-6688
 * @Description
 * @Create 2021-04-25 16:13
 */
@Controller
public class CartController {
    @Resource
    CartServiceImpl cartServiceImpl;

    /**
     * 远程调用使用，用于显示订单结算页面
     * @return
     */
    @GetMapping("/getOrderItem")
    public @ResponseBody List<OrderItemTo> getOrderItem(){
        return cartServiceImpl.getOrderItem();
    }

    @GetMapping("/checkItem")
    public String checkItem(@RequestParam Long skuId,@RequestParam Short checked){
        cartServiceImpl.checkItem(skuId, checked);
        return "redirect:http://cart.gulimall.com/cart.html";
    }

    @GetMapping("/countItem")
    public String countItem(@RequestParam Long skuId,@RequestParam Integer num){
        if(num == 0){
            cartServiceImpl.deleteItem(skuId);
        }else{
            cartServiceImpl.countItem(skuId, num);
        }
        return "redirect:http://cart.gulimall.com/cart.html";
    }

    @GetMapping("/deleteItem")
    public String deleteItem(@RequestParam Long skuId){
        cartServiceImpl.deleteItem(skuId);
        return "redirect:http://cart.gulimall.com/cart.html";
    }

    @RequestMapping("/cart.html")
    public String cart(Model model){
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        CartVo cartVo = cartServiceImpl.getCart(userInfoTo);
        model.addAttribute("cart",cartVo);
        return "cartList";
    }

    /**
     * 添加购物车数据，再重定向，进行查询
     * @param skuId
     * @param num
     * @param redirectAttributes
     * @return
     */
    @GetMapping("/addCartItem")
    public String addCartItem(@RequestParam Long skuId, @RequestParam Integer num, RedirectAttributes redirectAttributes){
        cartServiceImpl.addItem(skuId, num);
        redirectAttributes.addAttribute("skuId",skuId);     // 会将skuId作为参数发送请求
        return "redirect:http://cart.gulimall.com/addToCartSuccess.html";
    }

    @GetMapping("/addToCartSuccess.html")
    public String toCartSuccess(@RequestParam Long skuId,Model model){
        CartItemVo cartItemVo = cartServiceImpl.getCartItem(skuId);
        model.addAttribute("cartItem", cartItemVo);
        return "success";
    }
}
